<template>
	<view class="edit-address-container">
		<!-- 表单内容 -->
		<view class="form-container">
			<!-- 联系人 -->
			<view class="form-item">
				<text class="form-label">联系人</text>
				<input 
					class="form-input" 
					v-model="formData.contactName" 
					placeholder="请输入联系人姓名" />
			</view>

			<!-- 性别 -->
			<view class="form-item">
				<text class="form-label">性别</text>
				<view class="gender-options">
					<view 
						class="gender-option" 
						:class="{ 'active': formData.gender === 'male' }"
						@click="selectGender('male')">
						<view class="radio-btn">
							<u-icon 
								v-if="formData.gender === 'male'"
								name="checkmark" 
								size="20" 
								color="#fff">
							</u-icon>
						</view>
						<text class="gender-text">先生</text>
					</view>
					<view 
						class="gender-option" 
						:class="{ 'active': formData.gender === 'female' }"
						@click="selectGender('female')">
						<view class="radio-btn">
							<u-icon 
								v-if="formData.gender === 'female'"
								name="checkmark" 
								size="20" 
								color="#fff">
							</u-icon>
						</view>
						<text class="gender-text">女士</text>
					</view>
				</view>
			</view>

			<!-- 手机号 -->
			<view class="form-item">
				<text class="form-label">手机号</text>
				<input 
					class="form-input" 
					v-model="formData.phone" 
					placeholder="请输入手机号"
					type="number" />
			</view>

			<!-- 地址 -->
			<view class="form-item clickable" @click="selectLocation">
				<text class="form-label">地址</text>
				<view class="address-display">
					<text class="address-text">{{ displayAddress || '请选择地址' }}</text>
					<u-icon name="arrow-right" size="24" color="#ccc"></u-icon>
				</view>
			</view>

			<!-- 门牌号 -->
			<view class="form-item">
				<text class="form-label">门牌号</text>
				<input 
					class="form-input" 
					v-model="formData.houseNumber" 
					placeholder="请输入门牌号" />
			</view>

			<!-- 设为默认地址 -->
			<view class="form-item">
				<view class="default-option" @click="toggleDefault">
					<view class="default-checkbox" :class="{ 'checked': formData.isDefault }">
						<u-icon 
							v-if="formData.isDefault"
							name="checkmark" 
							size="20" 
							color="#fff">
						</u-icon>
					</view>
					<text class="default-text">设为默认地址</text>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-buttons">
			<view class="delete-btn" @click="deleteAddress" v-if="isEdit">
				<text class="delete-text">删除</text>
			</view>
			<view class="save-btn" @click="saveAddress">
				<text class="save-text">保存</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				action: 'add', // add 或 edit
				originalAddressData: null, // 原始地址数据
				formData: {
					id: null,
					contactName: '',
					gender: 'male',
					phone: '',
					province: '',
					city: '',
					district: '',
					address: '',
					houseNumber: '',
					isDefault: false
				}
			}
		},
		computed: {
			pageTitle() {
				return this.action === 'add' ? '新增地址' : '修改地址';
			},
			isEdit() {
				return this.action === 'edit';
			},
			displayAddress() {
				if (this.formData.province && this.formData.city && this.formData.address) {
					return `${this.formData.province}${this.formData.city}${this.formData.district} ${this.formData.address}`;
				}
				return this.formData.address;
			}
		},
		onLoad(options) {
			this.action = options.action || 'add';
			
			if (this.action === 'edit' && options.addressData) {
				try {
					// 解析传递过来的地址数据
					this.originalAddressData = JSON.parse(decodeURIComponent(options.addressData));
					this.loadAddressData();
				} catch (error) {
					console.error('解析地址数据失败:', error);
					uni.showToast({
						title: '加载地址信息失败',
						icon: 'none'
					});
				}
			}
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 加载地址数据到表单
			loadAddressData() {
				if (this.originalAddressData) {
					this.formData = {
						id: this.originalAddressData.id,
						contactName: this.originalAddressData.contactName || '',
						gender: this.originalAddressData.gender || 'male',
						phone: this.originalAddressData.phone || '',
						province: this.originalAddressData.province || '',
						city: this.originalAddressData.city || '',
						district: this.originalAddressData.district || '',
						address: this.originalAddressData.address || '',
						houseNumber: this.originalAddressData.houseNumber || '',
						isDefault: this.originalAddressData.isDefault || false
					};
				}
			},
			
			// 选择性别
			selectGender(gender) {
				this.formData.gender = gender;
			},
			
			// 选择地址
			selectLocation() {
				// 这里可以集成地图选择功能或者省市区选择器
				uni.showActionSheet({
					itemList: ['使用当前位置', '手动输入地址'],
					success: (res) => {
						if (res.tapIndex === 0) {
							// 获取当前位置
							this.getCurrentLocation();
						} else if (res.tapIndex === 1) {
							// 手动输入
							this.manualInputAddress();
						}
					}
				});
			},
			
			// 获取当前位置
			getCurrentLocation() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						// 这里可以根据经纬度反向解析地址
						uni.showToast({
							title: '定位成功',
							icon: 'success'
						});
						// 模拟设置地址
						this.formData.province = '湖南省';
						this.formData.city = '长沙市';
						this.formData.district = '岳麓区';
						this.formData.address = '麓谷小镇岳麓大道尖山路口北300米';
					},
					fail: (error) => {
						uni.showToast({
							title: '定位失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 手动输入地址
			manualInputAddress() {
				uni.showModal({
					title: '输入地址',
					editable: true,
					placeholderText: '请输入详细地址',
					success: (res) => {
						if (res.confirm && res.content) {
							this.formData.address = res.content;
							// 这里可以调用地址解析API
							this.parseAddress(res.content);
						}
					}
				});
			},
			
			// 解析地址（模拟）
			parseAddress(addressText) {
				// 这里应该调用真实的地址解析API
				// 暂时使用模拟数据
				if (addressText.includes('长沙')) {
					this.formData.province = '湖南省';
					this.formData.city = '长沙市';
					this.formData.district = '岳麓区';
				}
			},
			
			// 切换默认地址
			toggleDefault() {
				this.formData.isDefault = !this.formData.isDefault;
			},
			
			// 保存地址
			async saveAddress() {
				// 表单验证
				if (!this.formData.contactName.trim()) {
					uni.showToast({
						title: '请输入联系人姓名',
						icon: 'none'
					});
					return;
				}
				
				if (!this.formData.phone.trim()) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
					return;
				}
				
				// 验证手机号格式
				const phoneRegex = /^1[3-9]\d{9}$/;
				if (!phoneRegex.test(this.formData.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}
				
				if (!this.formData.address.trim()) {
					uni.showToast({
						title: '请选择地址',
						icon: 'none'
					});
					return;
				}
				
				try {
					// 构造完整地址
					const fullAddress = this.displayAddress + (this.formData.houseNumber ? ` ${this.formData.houseNumber}` : '');
					
					const addressData = {
						...this.formData,
						fullAddress: fullAddress
					};
					
					if (this.isEdit) {
						// 更新地址
						// await this.$http.put(`/api/address/${this.formData.id}`, addressData);
						console.log('更新地址:', addressData);
						uni.showToast({
							title: '地址更新成功',
							icon: 'success'
						});
					} else {
						// 新增地址
						// await this.$http.post('/api/address', addressData);
						console.log('新增地址:', addressData);
						uni.showToast({
							title: '地址添加成功',
							icon: 'success'
						});
					}
					
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} catch (error) {
					console.error('保存地址失败:', error);
					uni.showToast({
						title: '保存失败，请重试',
						icon: 'none'
					});
				}
			},
			
			// 删除地址
			deleteAddress() {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个地址吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								// await this.$http.delete(`/api/address/${this.formData.id}`);
								console.log('删除地址:', this.formData.id);
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
								
								setTimeout(() => {
									uni.navigateBack();
								}, 1500);
							} catch (error) {
								console.error('删除地址失败:', error);
								uni.showToast({
									title: '删除失败，请重试',
									icon: 'none'
								});
							}
						}
					}
				});
			}
		}
	}
</script>

<style scoped>
	.edit-address-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		padding-bottom: 120rpx;
	}

	/* 顶部导航栏 */
	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
	}

	.header-left {
		width: 60rpx;
	}

	.header-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.header-right {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.icon {
		font-size: 28rpx;
		color: #666;
	}

	.target-icon {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
		border: 3rpx solid #333;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #333;
	}

	/* 表单容器 */
	.form-container {
		padding: 30rpx;
	}

	.form-item {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 2rpx;
		display: flex;
		align-items: center;
	}

	.form-item.clickable {
		cursor: pointer;
	}

	.form-label {
		font-size: 28rpx;
		color: #333;
		width: 150rpx;
		flex-shrink: 0;
	}

	.form-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		padding: 0;
	}

	/* 性别选择 */
	.gender-options {
		display: flex;
		gap: 60rpx;
		flex: 1;
	}

	.gender-option {
		display: flex;
		align-items: center;
		gap: 15rpx;
		cursor: pointer;
	}

	.radio-btn {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		border: 2rpx solid #ddd;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.gender-option.active .radio-btn {
		background-color: #1976d2;
		border-color: #1976d2;
	}

	.gender-text {
		font-size: 28rpx;
		color: #333;
	}

	/* 地址显示 */
	.address-display {
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex: 1;
	}

	.address-text {
		font-size: 28rpx;
		color: #333;
		flex: 1;
	}

	/* 默认地址选项 */
	.default-option {
		display: flex;
		align-items: center;
		gap: 15rpx;
		cursor: pointer;
	}

	.default-checkbox {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		border: 2rpx solid #ddd;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.default-checkbox.checked {
		background-color: #1976d2;
		border-color: #1976d2;
	}

	.default-text {
		font-size: 28rpx;
		color: #333;
	}

	/* 底部按钮 */
	.bottom-buttons {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 30rpx;
		display: flex;
		gap: 30rpx;
		box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.delete-btn {
		flex: 1;
		background-color: #f0f0f0;
		padding: 25rpx;
		border-radius: 8rpx;
		text-align: center;
	}

	.delete-text {
		font-size: 28rpx;
		color: #666;
	}

	.save-btn {
		flex: 2;
		background-color: #1976d2;
		padding: 25rpx;
		border-radius: 8rpx;
		text-align: center;
	}

	.save-text {
		font-size: 28rpx;
		color: #fff;
		font-weight: bold;
	}
</style>
